﻿using Kingdee.BOS.App.Data;
using Kingdee.BOS.Core.DynamicForm.PlugIn;
using Kingdee.BOS.Core.DynamicForm.PlugIn.Args;
using Kingdee.BOS.Orm.DataEntity;
using Kingdee.BOS.Util;
using System.Collections.Generic;
using System.ComponentModel;

namespace LM.YF.K3Cloud.Plugin
{
    /// <summary>
    /// 审核销售出库单反写货运单货运状态
    /// <author>鹿奔</author>
    /// <date>240117</date>
    /// </summary>
    [Description("审核销售出库单反写货运单货运状态操作服务插件（挂载到销售出库单）"), HotUpdate]
    public class ReverseFreightStateOperationServicePlugin : AbstractOperationServicePlugIn
    {
        public override void BeforeExecuteOperationTransaction(BeforeExecuteOperationTransaction e)
        {
            base.BeforeExecuteOperationTransaction(e);

            var billType = BusinessInfo.GetForm().Id;
            // 如果不是销售出库单，则不执行
            if (!"SAL_OUTSTOCK".Equals(billType))
            {
                return;
            }

            if (FormOperation.OperationId == Kingdee.BOS.Core.Metadata.FormElement.FormOperation.Operation_Audit)
            {
                SetBillStatus2B(e);
            }
            else if (FormOperation.OperationId == Kingdee.BOS.Core.Metadata.FormElement.FormOperation.Operation_UnAudit)
            {
                SetBillStatus2A(e);
            }
        }

        /// <summary>
        /// 获取货运单内码
        /// </summary>
        /// <param name="e"></param>
        /// <returns></returns>
        private List<string> GetHydIds(BeforeExecuteOperationTransaction e)
        {
            var rows = e.SelectedRows;
            var hydIds = new List<string>();
            foreach (var row in rows)
            {
                var entries = row.DataEntity["SAL_OUTSTOCKENTRY"] as DynamicObjectCollection;
                foreach (var entry in entries)
                {
                    var entryId = entry["Id"]?.ToString();// 销售出库单FENTRYID
                    var hydId = DBUtils.ExecuteScalar<string>(Context, $@"select c.FID
                        from T_SAL_OUTSTOCKENTRY_LK as a-- 发货通知单下推销售出库单
                        inner join RDLV_t_DiliveOrdEntry_LK as b on b.FSTableName = 'T_SAL_DELIVERYNOTICEENTRY'
                            and b.FSId = a.FSID-- 发货通知单下推货运单
                        inner join RDLV_t_DiliveOrdEntry as c on c.FEntryID = b.FEntryID
                        where a.FSTABLENAME = 'T_SAL_DELIVERYNOTICEENTRY'
                            and a.FENTRYID = {entryId};", default);
                    if (hydId != null)
                    {
                        hydIds.Add(hydId);
                    }
                }
            }

            return hydIds;
        }

        /// <summary>
        /// 反审核
        /// </summary>
        /// <param name="e"></param>
        private void SetBillStatus2A(BeforeExecuteOperationTransaction e)
        {
            var hydIds = GetHydIds(e);
            if (hydIds.Count > 0)
            {
                var ids = string.Join(",", hydIds);
                DBUtils.Execute(Context, $@"update RDLV_t_DiliveOrder
                    set F_RDLV_BILLSTATUS = 'A'
                    where FID in ({ids});");
            }
        }

        private void SetBillStatus2B(BeforeExecuteOperationTransaction e)
        {
            var hydIds = GetHydIds(e);
            if (hydIds.Count > 0)
            {
                var ids = string.Join(",", hydIds);
                DBUtils.Execute(Context, $@"update RDLV_t_DiliveOrder
                    set F_RDLV_BILLSTATUS = 'B'
                    where FID in ({ids});");
            }
        }
    }
}
